// src/shared/service/productService.ts

import { Product, Category, ApiResponse, Pagination } from '../types';
import { STORAGE_KEYS, getStorageData, setStorageData } from '../utils/storage';
import { checkAdmin } from './userService';

// 生成UUID（简化版）
const generateProductUUID = (): string => {
  return 'prod_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
};

const generateCategoryUUID = (): string => {
  return 'cat_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
};

// ===== 商品查询功能（无需权限验证） =====

export interface ProductListQuery {
  page?: number;
  pageSize?: number;
  keyword?: string;
  categoryId?: string;
  sortBy?: 'price' | 'sales' | 'createdAt';
  sortOrder?: 'asc' | 'desc';
}

export interface ProductListResponse {
  products: Product[];
  pagination: Pagination;
}

/**
 * 获取商品列表
 */
export const getProducts = async (query: ProductListQuery = {}): Promise<ApiResponse<ProductListResponse>> => {
  try {
    const {
      page = 1,
      pageSize = 20,
      keyword,
      categoryId,
      sortBy = 'createdAt',
      sortOrder = 'desc'
    } = query;

    // 获取所有商品
    let products = getStorageData<Product>(STORAGE_KEYS.PRODUCTS);

    // 过滤掉非激活状态的商品（前台只显示激活商品）
    products = products.filter(product => product.status === 'active');

    // 关键词搜索（搜索名称和描述）
    if (keyword && keyword.trim()) {
      const searchTerm = keyword.trim().toLowerCase();
      products = products.filter(product =>
        product.name.toLowerCase().includes(searchTerm) ||
        product.description.toLowerCase().includes(searchTerm)
      );
    }

    // 分类筛选
    if (categoryId) {
      products = products.filter(product => product.categoryId === categoryId);
    }

    // 排序
    products.sort((a, b) => {
      let aValue: any, bValue: any;

      switch (sortBy) {
        case 'price':
          aValue = a.price;
          bValue = b.price;
          break;
        case 'sales':
          aValue = a.sales;
          bValue = b.sales;
          break;
        case 'createdAt':
        default:
          aValue = new Date(a.createdAt).getTime();
          bValue = new Date(b.createdAt).getTime();
          break;
      }

      if (sortOrder === 'asc') {
        return aValue - bValue;
      } else {
        return bValue - aValue;
      }
    });

    // 分页
    const total = products.length;
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedProducts = products.slice(startIndex, endIndex);

    return {
      code: 200,
      message: '获取商品列表成功',
      data: {
        products: paginatedProducts,
        pagination: {
          current: page,
          pageSize,
          total
        }
      }
    };

  } catch (error) {
    console.error('获取商品列表失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    };
  }
};

/**
 * 获取商品详情
 */
export const getProductById = async (productId: string): Promise<ApiResponse<{ product: Product }>> => {
  try {
    if (!productId) {
      return {
        code: 400,
        message: '商品ID不能为空',
        data: null
      };
    }

    const products = getStorageData<Product>(STORAGE_KEYS.PRODUCTS);
    const product = products.find(p => p.id === productId);

    if (!product) {
      return {
        code: 404,
        message: '商品不存在',
        data: null
      };
    }

    // 前台只能查看激活状态的商品
    if (product.status !== 'active') {
      return {
        code: 404,
        message: '商品不存在',
        data: null
      };
    }

    return {
      code: 200,
      message: '获取商品详情成功',
      data: {
        product
      }
    };

  } catch (error) {
    console.error('获取商品详情失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    };
  }
};

/**
 * 获取热门商品
 */
export const getHotProducts = async (): Promise<ApiResponse<{ products: Product[] }>> => {
  try {
    const hotProducts = getStorageData<Product>(STORAGE_KEYS.HOT_PRODUCTS);

    // 过滤激活状态的热门商品
    const activeHotProducts = hotProducts.filter(product => product.status === 'active');

    return {
      code: 200,
      message: '获取热门商品成功',
      data: {
        products: activeHotProducts
      }
    };

  } catch (error) {
    console.error('获取热门商品失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    };
  }
};

// ===== 分类功能 =====

/**
 * 获取分类列表
 */
export const getCategories = async (): Promise<ApiResponse<{ categories: Category[] }>> => {
  try {
    const categories = getStorageData<Category>(STORAGE_KEYS.CATEGORIES);

    return {
      code: 200,
      message: '获取分类列表成功',
      data: {
        categories
      }
    };

  } catch (error) {
    console.error('获取分类列表失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    };
  }
};

// ===== 管理员商品管理功能 =====

export interface CreateProductRequest {
  name: string;
  description: string;
  price: number;
  originalPrice?: number;
  coverImage: string;
  images: string[];
  categoryId: string;
  stock: number;
}

export interface UpdateProductRequest {
  name?: string;
  description?: string;
  price?: number;
  originalPrice?: number;
  coverImage?: string;
  images?: string[];
  categoryId?: string;
  stock?: number;
  status?: 'active' | 'inactive';
}

/**
 * 添加商品（管理员功能）
 */
export const createProduct = async (params: CreateProductRequest): Promise<ApiResponse<{ product: Product }>> => {
  try {
    // 检查管理员权限
    const adminResult = checkAdmin();
    if (!adminResult.success) {
      return adminResult.error!;
    }

    const { name, description, price, originalPrice, coverImage, images, categoryId, stock } = params;

    // 参数验证
    if (!name || !description || !coverImage || !categoryId) {
      return {
        code: 400,
        message: '商品名称、描述、封面图片和分类都是必填的',
        data: null
      };
    }

    if (price <= 0) {
      return {
        code: 400,
        message: '商品价格必须大于0',
        data: null
      };
    }

    if (stock < 0) {
      return {
        code: 400,
        message: '库存数量不能为负数',
        data: null
      };
    }

    // 验证分类是否存在
    const categories = getStorageData<Category>(STORAGE_KEYS.CATEGORIES);
    const categoryExists = categories.some(cat => cat.id === categoryId);
    if (!categoryExists) {
      return {
        code: 400,
        message: '指定的分类不存在',
        data: null
      };
    }

    // 创建新商品
    const now = new Date().toISOString();
    const newProduct: Product = {
      id: generateProductUUID(),
      name: name.trim(),
      description: description.trim(),
      price,
      originalPrice,
      coverImage: coverImage.trim(),
      images: images || [],
      categoryId,
      stock,
      sales: 0, // 新商品销量为0
      status: 'active',
      createdAt: now,
      updatedAt: now
    };

    // 保存到localStorage
    const products = getStorageData<Product>(STORAGE_KEYS.PRODUCTS);
    const updatedProducts = [...products, newProduct];
    setStorageData(STORAGE_KEYS.PRODUCTS, updatedProducts);

    return {
      code: 200,
      message: '商品添加成功',
      data: {
        product: newProduct
      }
    };

  } catch (error) {
    console.error('添加商品失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    };
  }
};

/**
 * 更新商品信息（管理员功能）
 */
export const updateProduct = async (productId: string, params: UpdateProductRequest): Promise<ApiResponse<{ product: Product }>> => {
  try {
    // 检查管理员权限
    const adminResult = checkAdmin();
    if (!adminResult.success) {
      return adminResult.error!;
    }

    if (!productId) {
      return {
        code: 400,
        message: '商品ID不能为空',
        data: null
      };
    }

    // 获取商品数据
    const products = getStorageData<Product>(STORAGE_KEYS.PRODUCTS);
    const productIndex = products.findIndex(p => p.id === productId);

    if (productIndex === -1) {
      return {
        code: 404,
        message: '商品不存在',
        data: null
      };
    }

    const { name, description, price, originalPrice, coverImage, images, categoryId, stock, status } = params;

    // 参数验证
    if (price !== undefined && price <= 0) {
      return {
        code: 400,
        message: '商品价格必须大于0',
        data: null
      };
    }

    if (stock !== undefined && stock < 0) {
      return {
        code: 400,
        message: '库存数量不能为负数',
        data: null
      };
    }

    // 验证分类是否存在
    if (categoryId) {
      const categories = getStorageData<Category>(STORAGE_KEYS.CATEGORIES);
      const categoryExists = categories.some(cat => cat.id === categoryId);
      if (!categoryExists) {
        return {
          code: 400,
          message: '指定的分类不存在',
          data: null
        };
      }
    }

    // 更新商品
    const originalProduct = products[productIndex];
    const updatedProduct: Product = {
      ...originalProduct,
      name: name?.trim() ?? originalProduct.name,
      description: description?.trim() ?? originalProduct.description,
      price: price ?? originalProduct.price,
      originalPrice: originalPrice !== undefined ? originalPrice : originalProduct.originalPrice,
      coverImage: coverImage?.trim() ?? originalProduct.coverImage,
      images: images ?? originalProduct.images,
      categoryId: categoryId ?? originalProduct.categoryId,
      stock: stock ?? originalProduct.stock,
      status: status ?? originalProduct.status,
      updatedAt: new Date().toISOString()
    };

    products[productIndex] = updatedProduct;
    setStorageData(STORAGE_KEYS.PRODUCTS, products);

    return {
      code: 200,
      message: '商品更新成功',
      data: {
        product: updatedProduct
      }
    };

  } catch (error) {
    console.error('更新商品失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    };
  }
};

/**
 * 删除商品（软删除，管理员功能）
 */
export const deleteProduct = async (productId: string): Promise<ApiResponse<null>> => {
  try {
    // 检查管理员权限
    const adminResult = checkAdmin();
    if (!adminResult.success) {
      return adminResult.error!;
    }

    if (!productId) {
      return {
        code: 400,
        message: '商品ID不能为空',
        data: null
      };
    }

    // 获取商品数据
    const products = getStorageData<Product>(STORAGE_KEYS.PRODUCTS);
    const productIndex = products.findIndex(p => p.id === productId);

    if (productIndex === -1) {
      return {
        code: 404,
        message: '商品不存在',
        data: null
      };
    }

    // 软删除：设置状态为inactive
    products[productIndex] = {
      ...products[productIndex],
      status: 'inactive',
      updatedAt: new Date().toISOString()
    };

    setStorageData(STORAGE_KEYS.PRODUCTS, products);

    return {
      code: 200,
      message: '商品删除成功',
      data: null
    };

  } catch (error) {
    console.error('删除商品失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    };
  }
};

/**
 * 获取所有商品（管理员功能，包括非激活商品）
 */
export const getAllProductsForAdmin = async (query: ProductListQuery = {}): Promise<ApiResponse<ProductListResponse>> => {
  try {
    // 检查管理员权限
    const adminResult = checkAdmin();
    if (!adminResult.success) {
      return adminResult.error!;
    }

    const {
      page = 1,
      pageSize = 20,
      keyword,
      categoryId,
      sortBy = 'createdAt',
      sortOrder = 'desc'
    } = query;

    // 获取所有商品（包括非激活的）
    let products = getStorageData<Product>(STORAGE_KEYS.PRODUCTS);

    // 关键词搜索
    if (keyword && keyword.trim()) {
      const searchTerm = keyword.trim().toLowerCase();
      products = products.filter(product =>
        product.name.toLowerCase().includes(searchTerm) ||
        product.description.toLowerCase().includes(searchTerm)
      );
    }

    // 分类筛选
    if (categoryId) {
      products = products.filter(product => product.categoryId === categoryId);
    }

    // 排序
    products.sort((a, b) => {
      let aValue: any, bValue: any;

      switch (sortBy) {
        case 'price':
          aValue = a.price;
          bValue = b.price;
          break;
        case 'sales':
          aValue = a.sales;
          bValue = b.sales;
          break;
        case 'createdAt':
        default:
          aValue = new Date(a.createdAt).getTime();
          bValue = new Date(b.createdAt).getTime();
          break;
      }

      if (sortOrder === 'asc') {
        return aValue - bValue;
      } else {
        return bValue - aValue;
      }
    });

    // 分页
    const total = products.length;
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedProducts = products.slice(startIndex, endIndex);

    return {
      code: 200,
      message: '获取商品列表成功',
      data: {
        products: paginatedProducts,
        pagination: {
          current: page,
          pageSize,
          total
        }
      }
    };

  } catch (error) {
    console.error('获取商品列表失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    };
  }
};

// ===== 管理员分类管理功能 =====

export interface CreateCategoryRequest {
  name: string;
  icon?: string;
}

export interface UpdateCategoryRequest {
  name?: string;
  icon?: string;
}

/**
 * 添加分类（管理员功能）
 */
export const createCategory = async (params: CreateCategoryRequest): Promise<ApiResponse<{ category: Category }>> => {
  try {
    // 检查管理员权限
    const adminResult = checkAdmin();
    if (!adminResult.success) {
      return adminResult.error!;
    }

    const { name, icon } = params;

    if (!name || !name.trim()) {
      return {
        code: 400,
        message: '分类名称不能为空',
        data: null
      };
    }

    // 检查分类名称是否已存在
    const categories = getStorageData<Category>(STORAGE_KEYS.CATEGORIES);
    const existingCategory = categories.find(cat => cat.name === name.trim());
    if (existingCategory) {
      return {
        code: 409,
        message: '分类名称已存在',
        data: null
      };
    }

    // 创建新分类
    const newCategory: Category = {
      id: generateCategoryUUID(),
      name: name.trim(),
      icon: icon?.trim()
    };

    const updatedCategories = [...categories, newCategory];
    setStorageData(STORAGE_KEYS.CATEGORIES, updatedCategories);

    return {
      code: 200,
      message: '分类添加成功',
      data: {
        category: newCategory
      }
    };

  } catch (error) {
    console.error('添加分类失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    };
  }
};

/**
 * 更新分类（管理员功能）
 */
export const updateCategory = async (categoryId: string, params: UpdateCategoryRequest): Promise<ApiResponse<{ category: Category }>> => {
  try {
    // 检查管理员权限
    const adminResult = checkAdmin();
    if (!adminResult.success) {
      return adminResult.error!;
    }

    if (!categoryId) {
      return {
        code: 400,
        message: '分类ID不能为空',
        data: null
      };
    }

    const { name, icon } = params;
    const categories = getStorageData<Category>(STORAGE_KEYS.CATEGORIES);
    const categoryIndex = categories.findIndex(cat => cat.id === categoryId);

    if (categoryIndex === -1) {
      return {
        code: 404,
        message: '分类不存在',
        data: null
      };
    }

    // 如果要更新名称，检查是否与其他分类重名
    if (name && name.trim()) {
      const existingCategory = categories.find(cat => cat.name === name.trim() && cat.id !== categoryId);
      if (existingCategory) {
        return {
          code: 409,
          message: '分类名称已存在',
          data: null
        };
      }
    }

    // 更新分类
    const originalCategory = categories[categoryIndex];
    const updatedCategory: Category = {
      ...originalCategory,
      name: name?.trim() ?? originalCategory.name,
      icon: icon !== undefined ? icon?.trim() : originalCategory.icon
    };

    categories[categoryIndex] = updatedCategory;
    setStorageData(STORAGE_KEYS.CATEGORIES, categories);

    return {
      code: 200,
      message: '分类更新成功',
      data: {
        category: updatedCategory
      }
    };

  } catch (error) {
    console.error('更新分类失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    };
  }
};

/**
 * 删除分类（管理员功能）
 */
export const deleteCategory = async (categoryId: string): Promise<ApiResponse<null>> => {
  try {
    // 检查管理员权限
    const adminResult = checkAdmin();
    if (!adminResult.success) {
      return adminResult.error!;
    }

    if (!categoryId) {
      return {
        code: 400,
        message: '分类ID不能为空',
        data: null
      };
    }

    const categories = getStorageData<Category>(STORAGE_KEYS.CATEGORIES);
    const categoryExists = categories.some(cat => cat.id === categoryId);

    if (!categoryExists) {
      return {
        code: 404,
        message: '分类不存在',
        data: null
      };
    }

    // 检查是否有商品使用该分类
    const products = getStorageData<Product>(STORAGE_KEYS.PRODUCTS);
    const hasProducts = products.some(product => product.categoryId === categoryId);

    if (hasProducts) {
      return {
        code: 409,
        message: '该分类下还有商品，无法删除',
        data: null
      };
    }

    // 删除分类
    const updatedCategories = categories.filter(cat => cat.id !== categoryId);
    setStorageData(STORAGE_KEYS.CATEGORIES, updatedCategories);

    return {
      code: 200,
      message: '分类删除成功',
      data: null
    };

  } catch (error) {
    console.error('删除分类失败:', error);
    return {
      code: 500,
      message: '服务器内部错误',
      data: null
    };
  }
};